package ua.org.nuos.sdms.middle.service;

import ua.org.nuos.configuration.SdmsConfiguration;
import ua.org.nuos.sdms.middle.dao.EmailVerificationDaoBean;
import ua.org.nuos.sdms.middle.dao.UserDaoBean;
import ua.org.nuos.sdms.middle.entity.EmailVerification;
import ua.org.nuos.sdms.middle.entity.User;
import ua.org.nuos.sdms.middle.entity.enums.EmailStatus;
import ua.org.nuos.sdms.middle.util.CodeUtil;
import ua.org.nuos.sdms.middle.util.MailMessageConstructor;
import ua.org.nuos.sdms.middle.util.exception.EmailVerificationException;
import ua.org.nuos.sdms.middle.vo.CustomMessage;

import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 * User: Denis Fahritdinov
 * Date: 10/7/12
 * Time: 4:39 PM
 */
@Stateless
public class EmailVerificationServiceBean implements EmailVerificationServiceLocal {

    @EJB(beanName = "UserDaoBean")
    protected UserDaoBean userDaoBean;

    @EJB(beanName = "EmailVerificationDaoBean")
    protected EmailVerificationDaoBean emailVerificationDao;

    @EJB(beanName = "AuthenticationBean")
    protected AuthenticationLocal authentication;

    @EJB(beanName = "MailSenderServiceBean")
    protected MailSenderServiceBean mailSenderServiceBean;

    @EJB(beanName = "SdmsConfiguration")
    protected SdmsConfiguration configuration;

    @Override
    public void sendEmailVerificationMessage() {
        User currentUser = authentication.getCurrentUser();
        String code = CodeUtil.createRandomCode();
        CustomMessage message = MailMessageConstructor.createEmailVerificationMessage(
                currentUser.getEmail(), configuration.getClientGuiHost(), code);
        mailSenderServiceBean.sendMessage(message);

        emailVerificationDao.remove(currentUser.getId());
        EmailVerification emailVerification = new EmailVerification(currentUser, code);
        emailVerificationDao.create(emailVerification);

        currentUser.setEmailStatus(EmailStatus.UNKNOWN);
        userDaoBean.update(currentUser);
    }

    @Override
    public void completeEmailVerification(String code) throws EmailVerificationException {
        User currentUser = authentication.getCurrentUser();
        if (currentUser.getEmailStatus().equals(EmailStatus.UNKNOWN)) {
            EmailVerification emailVerification = emailVerificationDao.find(code);
            if (emailVerification == null) {
                throw new EmailVerificationException(code);
            } else {
                emailVerification.getUser().setEmailStatus(EmailStatus.VALID);
                userDaoBean.update(emailVerification.getUser());
                emailVerificationDao.remove(emailVerification.getUser().getId());
            }
        }
    }

    @Override
    public boolean isEmailValid() {
        User currentUser = authentication.getCurrentUser();
        return currentUser.getEmailStatus().equals(EmailStatus.VALID);
    }
}
